# Boa:Frame:Frame1

import wx
import wx.grid
import sys
import Updatedb_Dialog1
import lottery_about
import lotto_db
import history_view
import number_statistics
import statistics
import picks

# import wx.lib.clipboard


def create(parent):
    return Frame1(parent)

[wxID_FRAME1] = [wx.NewId() for _init_ctrls in range(1)]

[wxID_FRAME1FILEMENUCLOSEDB, wxID_FRAME1FILEMENUEXITITEM,
 wxID_FRAME1FILEMENUOPENDB, wxID_FRAME1FILEMENUUPDATEDB,
 ] = [wx.NewId() for _init_coll_FileMenu_Items in range(4)]

[wxID_FRAME1MENU1ITEMS0, wxID_FRAME1MENU1ITEMS1, wxID_FRAME1MENU1ITEMS2,
 ] = [wx.NewId() for _init_coll_EditMenu_Items in range(3)]

[wxID_FRAME1HELPMENUITEMS0, wxID_FRAME1HELPMENUITEMSABOUT] = [
    wx.NewId() for _init_coll_HelpMenu_Items in range(2)]

[wxID_FRAME1VIEWMENUITEMSHISTORY, wxID_FRAME1VIEWMENUITEMSNUMBER,
 wxID_FRAME1VIEWMENUITEMSPICKS,
 ] = [wx.NewId() for _init_coll_ViewMenu_Items in range(3)]


class Frame1(wx.Frame):

    def _init_coll_EditMenu_Items(self, parent):
        # generated method, don't edit

        parent.Append(help='', id=wxID_FRAME1MENU1ITEMS0, kind=wx.ITEM_NORMAL,
                      text='Cut')
        parent.Append(help='', id=wxID_FRAME1MENU1ITEMS1, kind=wx.ITEM_NORMAL,
                      text='Copy')
        parent.Append(help='', id=wxID_FRAME1MENU1ITEMS2, kind=wx.ITEM_NORMAL,
                      text='Paste')

    def _init_coll_ViewMenu_Items(self, parent):
        # generate view menu items
        parent.Append(help="View the complete draw history",
                      id=wxID_FRAME1VIEWMENUITEMSHISTORY,
                       kind=wx.ITEM_NORMAL, text='History...')
        parent.Append(help="View individual number statistics",
                      id=wxID_FRAME1VIEWMENUITEMSNUMBER,
                       kind=wx.ITEM_NORMAL, text='Number...')
        parent.Append(help="View best computer guess",
                      id=wxID_FRAME1VIEWMENUITEMSPICKS,
                       kind=wx.ITEM_NORMAL, text='Picks...')
        self.Bind(wx.EVT_MENU, self.OnViewMenuHistoryMenu,
                  id=wxID_FRAME1VIEWMENUITEMSHISTORY)
        self.Bind(wx.EVT_MENU, self.OnViewMenuStatsMenu,
                  id=wxID_FRAME1VIEWMENUITEMSNUMBER)
        self.Bind(wx.EVT_MENU, self.OnViewMenuPicksMenu,
                  id=wxID_FRAME1VIEWMENUITEMSPICKS)

    def _init_coll_menuBar1_Menus(self, parent):
        # generated method, don't edit

        parent.Append(self.FileMenu, 'File')
        parent.Append(self.EditMenu, 'Edit')
        parent.Append(self.ViewMenu, 'View')
        parent.Append(self.HelpMenu, 'Help')

    def _init_coll_HelpMenu_Items(self, parent):
        # generated method, don't edit

        parent.Append(help='', id=wxID_FRAME1HELPMENUITEMS0,
                      kind=wx.ITEM_NORMAL, text='Help')
        parent.Append(help='', id=wxID_FRAME1HELPMENUITEMSABOUT,
                      kind=wx.ITEM_NORMAL, text='About')
        self.Bind(wx.EVT_MENU, self.OnHelpMenuAboutMenu,
                  id=wxID_FRAME1HELPMENUITEMSABOUT)

    def _init_coll_FileMenu_Items(self, parent):
        # generated method, don't edit

        parent.Append(help='Open a database', id=wxID_FRAME1FILEMENUOPENDB,
                      kind=wx.ITEM_NORMAL, text='Open database')
        parent.Append(help='Update the database',
                      id=wxID_FRAME1FILEMENUUPDATEDB, kind=wx.ITEM_NORMAL,
                      text='Update database...')
        parent.Append(help='', id=wxID_FRAME1FILEMENUEXITITEM,
                      kind=wx.ITEM_NORMAL, text='Exit')

        self.Bind(wx.EVT_MENU, self.OnFileMenuExititemMenu,
                  id=wxID_FRAME1FILEMENUEXITITEM)
        self.Bind(wx.EVT_MENU, self.OnFileMenuUpdateDBMenu,
                  id=wxID_FRAME1FILEMENUUPDATEDB)
        self.Bind(wx.EVT_MENU, self.OnFileMenuOpenDB,
                    id=wxID_FRAME1FILEMENUOPENDB)
        self.Bind(wx.EVT_MENU, self.OnCopyTable, id=wxID_FRAME1MENU1ITEMS1)

    def _init_utils(self):
        # generated method, don't edit

        self.menuBar1 = wx.MenuBar()
        self.FileMenu = wx.Menu()
        self.EditMenu = wx.Menu()
        self.ViewMenu = wx.Menu()
        self.HelpMenu = wx.Menu()

        self._init_coll_FileMenu_Items(self.FileMenu)
        self._init_coll_EditMenu_Items(self.EditMenu)
        self._init_coll_ViewMenu_Items(self.ViewMenu)
        self._init_coll_HelpMenu_Items(self.HelpMenu)
        self._init_coll_menuBar1_Menus(self.menuBar1)

        self.panel1 = wx.Panel(self)
        self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL)

        self.grid_1 = wx.grid.Grid(self.panel1, wx.EXPAND)
        self.grid_1.CreateGrid(10, 5)
        self.grid_1.SetColLabelSize(48)
        self.grid_1.SetColLabelAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
        self.grid_1.SetColLabelValue(0, "Most\n Frequent")
        self.grid_1.SetColLabelValue(1, "Overdue")
        self.grid_1.SetColLabelValue(2, "Best skip \n now")
        self.grid_1.SetColLabelValue(3, "Skip count")
        self.grid_1.SetColLabelValue(4, "Next \nbest skip")
        self.grid_1.AutoSize()
        self.grid_1.EnableEditing(False)

        self.sizer_1.SetSizeHints(self)
        self.sizer_1.Add(self.grid_1, wx.EXPAND, 1)
        self.panel1.SetSizer(self.sizer_1)
        self.panel1.SetSize(self.grid_1.GetSize() + (20, 20))

    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
                          pos=wx.Point(775, 309),
                          style=wx.DEFAULT_FRAME_STYLE,
                          title='Lottery Analysis')
        self._init_utils()
        self.SetClientSize(self.panel1.GetSize() + (10, 10))
        self.sb = self.CreateStatusBar()

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.SetMenuBar(self.menuBar1)
        self.menuBar1.Show()

        # TODO: insert selection of databases
        self.dbconn = lotto_db.lotto_db()

        self.UpdateGrid()

    def OnFileMenuExititemMenu(self, event):
        sys.exit()

    def OnFileMenuUpdateDBMenu(self, event):
        self.sb.SetStatusText("Updating database")
        last_date_row = self.dbconn.get_last_row("dates")[0]
        last_date = last_date_row[1]
        updatedb_dialog = Updatedb_Dialog1.create(self)
        last_draw_date = wx.DateTime()
        last_draw_date.ParseDate(str(last_date))
        updatedb_dialog.SetPickDate(str(last_draw_date))
        updatedb_dialog.ShowModal()
        first = updatedb_dialog.GetFirstNumber()
        second = updatedb_dialog.GetSecondNumber()
        third = updatedb_dialog.GetThirdNumber()
        fourth = updatedb_dialog.GetFourthNumber()
        fifth = updatedb_dialog.GetFifthNumber()
        pb = updatedb_dialog.GetPowerball()
        date = updatedb_dialog.GetDateInput()
        if first and second and third and fourth and fifth and pb:
            self.dbconn.update_database(
                date, first, second, third, fourth, fifth, pb)
        self.UpdateGrid()

    def OnFileMenuOpenDB(self, event):
        selectDB = wx.FileDialog(self)
        warnDB = wx.MessageDialog(self,
            message="This will clear the statistics",
            caption="Open database",
            style=wx.CANCEL | wx.OK)
        clearIt = warnDB.ShowModal()
        print clearIt
        if clearIt == wx.ID_OK:
            selectDB.ShowModal()

    def OnHelpMenuAboutMenu(self, event):
        about_dialog = lottery_about.AboutLotteryAnalysis(self)
        about_dialog.show()

    def UpdateGrid(self):
        self.sb.SetStatusText("Updating display....")
        freq_counts = []
        skip_counts = []
        overdue_dates = []
        skip_due = []
        next_best_skip = []
        self.sb.SetStatusText(self.sb.GetStatusText() + "calculating skips")

        for i in range(1, 60):
            number_table = "whiteball_" + str(i)
            draw_row, draw_count = self.dbconn.get_last_row(number_table)
            overdue_dates.append((draw_row[0], i))
            freq_counts.append((draw_count, i))
            best_skip, second_skip, third_skip = self.dbconn.get_highest_skips(
                i)
            best_skip_number, best_skip_count = self.dbconn.get_highest_skip(i)
            skip_counts.append((second_skip, third_skip, i))
            current_skip = self.dbconn.get_current_skip(i)
            if best_skip_number == current_skip:
                skip_due.append((best_skip_count, best_skip_number, i))
            if second_skip == current_skip:
                next_best_skip.append(i)
            if third_skip == current_skip:
                next_best_skip.append(i)
        self.sb.SetStatusText("Updating display...getting stats")
        freq_counts.sort()
        freq_counts.reverse()
        skip_counts.sort()
        skip_counts.reverse()
        overdue_dates.sort()

        for i in range(0, 11):
            self.grid_1.SetCellValue(i, 0, str(freq_counts[i][1]))
            self.grid_1.SetCellValue(i, 1, str(overdue_dates[i][1]))
            self.grid_1.SetCellValue(i, 2, " ")
            self.grid_1.SetCellValue(i, 4, " ")
        x = 0
        for i in skip_due:
            self.grid_1.SetCellValue(x, 2, str(i[2]))
            self.grid_1.SetCellValue(x, 3, str(i[1]))
            x += 1
        x = 0
        for i in next_best_skip:
            self.grid_1.SetCellValue(x, 4, str(i))
            x += 1
        print (self.find_best_stddev())
        self.grid_1.ForceRefresh()
        self.sb.SetStatusText("")

    def OnViewMenuHistoryMenu(self, event):
        history_viewer = history_view.HistoryView(self)
        history_viewer.ShowModal()

    def OnViewMenuStatsMenu(self, event):
        stats_viewer = number_statistics.NumberStats(self)
        stats_viewer.ShowModal()

    def OnViewMenuPicksMenu(self, event):
        picks_viewer = picks.Picks(self.dbconn)
        picks_viewer.ShowModal()

    def OnCopyTable(self, event):
        cell_values = ""
        clip_data = wx.TextDataObject()
        cells = self.grid_1.GetSelectedCols()
        if cells == []:
            cells = self.grid_1.GetSelectedRows()
            if cells == []:
                top_left = self.grid_1.GetSelectionBlockTopLeft()
                if top_left == []:
                    cells = str(self.grid_1.GetSelectedCells())
                    cell_values = cells
                else:
                    bottom_right = self.grid_1.GetSelectionBlockBottomRight()
                    for column in range(top_left[0][0], bottom_right[0][0] + 1):
                        for row in range(
                            top_left[0][1], bottom_right[0][1] + 1):
                            cell = str(self.grid_1.GetCellValue(column, row))
                            cell_values = cell_values + cell + " "
            else:
                for cell in range(0, 11):
                    cell_values = cell_values + \
                        str(self.grid_1.GetCellValue(cells[0], cell)) + " "
        else:
            for cell in range(0, 5):
                cell_values = cell_values + \
                    str(self.grid_1.GetCellValue(cell, cells[0])) + " "
        wx.TheClipboard.Open()
        clip_data.SetText(cell_values)
        wx.TheClipboard.SetData(clip_data)
        wx.TheClipboard.Close()

    def find_best_stddev(self):
        skip_in_variance = []
        #run through all the numbers and see which skips are ready
        for i in range(1, 60):
            population = self.dbconn.get_skip(i)
            mean, stddev = statistics.getStdDev(population)
            current = self.dbconn.get_current_skip(i)
            if current < (mean + stddev) or current > (mean - stddev):
                skip_in_variance.append([i, current])
            print ("\nMean=" + str(mean) + " Stand. Dev.=" + str(stddev))
        return skip_in_variance